﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace Data
{
    public  class ConvertTo
    {
      /*  public static DataTable ToDataTable<T>(IEnumerable<T> q)
        {
            DataTable dt = new DataTable();
            if (q == null || q.Count()==0)
            {
                return dt;
            }

            PropertyInfo[] info = null;
            foreach (T rec in q)
            {
                if (info == null)
                {
                    info = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo i in info)
                    {
                        Type colType = i.PropertyType;
                        if (colType.IsGenericType && colType.GetGenericTypeDefinition() == typeof(Nullable<>))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        dt.Columns.Add(new DataColumn(i.Name, colType));
                    }
                }
                DataRow dr = dt.NewRow();
                foreach (PropertyInfo i in info)
                {
                    dr[i.Name] = i.GetValue(rec, null) == null ? DBNull.Value : i.GetValue(rec, null);
                }
                dt.Rows.Add(dr);
            }

            return dt;

        }
       */
       public static DataTable ListToDataTable<T>(IEnumerable<T> list)
        {
            var dt = new DataTable();

            foreach (var info in typeof(T).GetProperties())
            {
                dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
            }
            foreach (var t in list)
            {
                var row = dt.NewRow();
                foreach (var info in typeof(T).GetProperties())
                {
                    row[info.Name] = info.GetValue(t, null);
                }
                dt.Rows.Add(row);
            }
            return dt;
        }

    }
}
